//
//  TrainChangeDetailsController.swift
//  AirTravel
//
//  Created by apple on 2021/8/28.
//

import UIKit
import Moya
import SwiftyJSON
import FWPopupView

class TrainChangeDetailsController: UIViewController {
    @IBOutlet weak var submit: UIButton!
    
    @IBOutlet weak var seatNameLab: UILabel!
    @IBOutlet weak var priceLab: UILabel!
    @IBOutlet weak var phoneLab: UILabel!
    @IBOutlet weak var namelab: UILabel!
    @IBOutlet weak var idCardLab: UILabel!
    
    /// 改签终点站
    @IBOutlet weak var changeTerminalLab: UILabel!
    /// 改签终点站小时
    @IBOutlet weak var changeTerminalHoursLab: UILabel!
    /// 改签终点站日期
    @IBOutlet weak var changeTerminalTimeLab: UILabel!
    /// 改签车次
    @IBOutlet weak var changeTrainsLab: UILabel!
    /// 改签时长
    @IBOutlet weak var changeLengthLab: UILabel!
    
    /// 改签出发站
    @IBOutlet weak var changeSetOutLab: UILabel!
    /// 改签出发小时
    @IBOutlet weak var changeSetOutHoursLab: UILabel!
    /// 改签出发时间
    @IBOutlet weak var changeSetOutTimeLab: UILabel!
    /// 改签
    @IBOutlet weak var changeLab: UILabel!
    
    /// 原终点站
    @IBOutlet weak var oldTerminalLab: UILabel!
    /// 原终点站小时
    @IBOutlet weak var oldTerminalHoursLab: UILabel!
    ///原终点站日期
    @IBOutlet weak var oldTerminalTimeLab: UILabel!
    /// 原出发站
    @IBOutlet weak var oldSetOutStandingLab: UILabel!
    /// 原小时
    @IBOutlet weak var oldSetOutHoursLab: UILabel!
    /// 原出发日期
    @IBOutlet weak var oldSetOutTimeLab: UILabel!
    @IBOutlet weak var oldLab: UILabel!
    
    /// 时长
    @IBOutlet weak var lengthLab: UILabel!
    /// 车次
    @IBOutlet weak var trainsLab: UILabel!
    
    var dataDic : Dictionary<String,Any>?
    var seatDic : Dictionary<String,Any>?
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    var payType = ""
    var change_amount = 0
    
    
    lazy var payView: ChoosePayView = {
        let customPopupView = ChoosePayView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 320))
        customPopupView.delegate = self
        customPopupView.layer.cornerRadius = 5
        customPopupView.layer.masksToBounds = true
        let vProperty = FWPopupViewProperty()
        vProperty.popupCustomAlignment = .bottomCenter
        vProperty.backgroundColor = UIColor.white
        vProperty.popupAnimationType = .frame
        vProperty.maskViewColor = UIColor(white: 0, alpha: 0.5)
        vProperty.touchWildToHide = "0"
        vProperty.popupViewEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        vProperty.animationDuration = 0.3
        customPopupView.vProperty = vProperty
    
        return customPopupView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = false
        self.navigationController?.navigationBar.tintColor = UIColor.black
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.black]
        NotificationCenter.default.addObserver(self, selector: #selector(aliPayClicks), name: Notification.Name("aliPaySucceess"), object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.tintColor = UIColor.white
        self.navigationController?.navigationBar.titleTextAttributes = [
            NSAttributedString.Key.foregroundColor : UIColor.white]
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "确认改签"
        self.oldLab.layer.cornerRadius = 2
        self.oldLab.layer.masksToBounds = true
        self.changeLab.layer.cornerRadius = 2
        self.changeLab.layer.masksToBounds = true
        self.submit.layer.cornerRadius = 6
        self.submit.layer.masksToBounds = true
        
        
        let gradientLayer0 = CAGradientLayer()
        gradientLayer0.cornerRadius = 3
        gradientLayer0.frame = self.submit.bounds
        gradientLayer0.colors = [
            UIColor(red: 101.0 / 255.0, green: 160.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0).cgColor,
            UIColor(red: 48.0 / 255.0, green: 124.0 / 255.0, blue: 248.0 / 255.0, alpha: 1.0).cgColor]
        gradientLayer0.locations = [0, 1]
        gradientLayer0.startPoint = CGPoint(x: 0, y: 1)
        gradientLayer0.endPoint = CGPoint(x: 1, y: 1)
        self.submit.layer.addSublayer(gradientLayer0)
        
        let toStationName = UserDefaults.standard.object(forKey: "xn_toStationName")
        self.oldTerminalLab.text = "\(toStationName ?? "")"
        let fromStationName = UserDefaults.standard.object(forKey: "xn_fromStationName")
        self.oldSetOutStandingLab.text = "\(fromStationName ?? "")"
        let departDate = UserDefaults.standard.object(forKey: "xn_departDate")
        self.oldSetOutTimeLab.text = "\(departDate ?? "")"
        let arriveDate = UserDefaults.standard.object(forKey: "xn_arriveDate")
        self.oldTerminalTimeLab.text = "\(arriveDate ?? "")"
        let departTime = UserDefaults.standard.object(forKey: "xn_departTime")
        self.oldSetOutHoursLab.text = "\(departTime ?? "")"
        let arriveTime = UserDefaults.standard.object(forKey: "xn_arriveTime")
        self.oldTerminalHoursLab.text = "\(arriveTime ?? "")"
        let useTime = UserDefaults.standard.object(forKey: "xn_useTime")
        self.lengthLab.text = "\(useTime ?? "")"
        let trainNo = UserDefaults.standard.object(forKey: "xn_trainNo")
        self.trainsLab.text = "\(trainNo ?? "")"
        
        let name = UserDefaults.standard.object(forKey: "xn_name")
        self.namelab.text = "\(name ?? "")"
        let number = UserDefaults.standard.object(forKey: "xn_number")
        self.idCardLab.text = "身份证:\(number ?? "")"
        
        let contactMobile = UserDefaults.standard.object(forKey: "xn_contactMobile")
        self.phoneLab.text = "\(contactMobile ?? "")"
        
        if let dic = self.dataDic {
            let durationMinutes = "\(dic["durationMinutes"] ?? "0")"
            let dur = Int(durationMinutes)
            let sfm = self.secondsToHoursMinutesSeconds(seconds: dur ?? 0)
            self.changeLengthLab.text = sfm
            self.changeTerminalLab.text = "\(dic["toStationName"] ?? "")"
            self.changeSetOutLab.text = "\(dic["fromStationName"] ?? "")"
            self.changeTerminalTimeLab.text = "\(dic["arriveDate"] ?? "")"
            self.changeTerminalHoursLab.text = "\(dic["arriveTime"] ?? "")"
            self.changeSetOutTimeLab.text = "\(dic["departDate"] ?? "")"
            self.changeSetOutHoursLab.text = "\(dic["startTime"] ?? "")"
            self.changeTrainsLab.text = "\(dic["trainNo"] ?? "")"
        }
        
        if let dic = self.seatDic {
            self.priceLab.text = "￥\(dic["maxPrice"] ?? "")"
            self.seatNameLab.text = "\(dic["seatName"] ?? "")"
        }
    }
    
    @objc func aliPayClicks(notifi : Notification) {
        YProgressHUD.showToast("改签成功")
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    func secondsToHoursMinutesSeconds(seconds:Int) -> (String) {
        let h = seconds/60
        let m = seconds%60
        if h > 0 {
            if m > 0 {
                return "\(h)时\(m)分"
            }
            return "\(h)时"
        }else{
            if m > 0 {
                return "\(m)分"
            }
            return ""
        }
    }

    @IBAction func submitBtn(_ sender: UIButton) {
        self.orderChange()
    }
    
    func orderChange() {
        let order_id = UserDefaults.standard.object(forKey: "xn_order_id")
        let ps_id = UserDefaults.standard.object(forKey: "xn_ps_id")
        guard let dic = self.dataDic else { return }
        guard let dict = self.seatDic else { return }

        let ticketTime = "\(dic["departDate"] ?? "")" + " \(dic["startTime"] ?? "")"
        let arrivalDateTime = "\(dic["arriveDate"] ?? "")" + " \(dic["arriveTime"] ?? "")"
        
        cancelableRequest = NetWorkRequest(API1.orderChangeQuery(parameters: ["order_id":"\(order_id ?? "")","ps_id":"\(ps_id ?? "")","changeDate":"\(dic["departDate"] ?? "")","ticketTime":ticketTime,"fromStationName":"\(dic["fromStationName"] ?? "")","toStationName":"\(dic["toStationName"] ?? "")","trainNo":"\(dic["trainNo"] ?? "")","arrivalDateTime":arrivalDateTime,"ticketPrice":"\(dict["maxPrice"] ?? "")","seatType":"\(dict["seatType"] ?? "")"]), completion: {[weak self] (responseString) -> (Void) in
            let change_status = responseString["data"]["change_status"].boolValue
            let change_amount = responseString["data"]["change_amount"].intValue
            self?.change_amount = change_amount
            if change_status == true {
                if change_amount > 0 {
                    self?.payView.show()
                }else{
                    self?.orderChangePay()
                }
            }else{
                YProgressHUD.showToast("改签失败")
            }
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }

    //改签支付接口地址
    func orderChangePay() {
        let order_id = UserDefaults.standard.object(forKey: "xn_order_id")
        let ps_id = UserDefaults.standard.object(forKey: "xn_ps_id")
        guard let dic = self.dataDic else { return }
        guard let dict = self.seatDic else { return }
        let ticketTime = "\(dic["departDate"] ?? "")" + " \(dic["startTime"] ?? "")"
        let arrivalDateTime = "\(dic["arriveDate"] ?? "")" + " \(dic["arriveTime"] ?? "")"
        
        cancelableRequest = NetWorkRequest(API1.orderChangePay(parameters: ["order_id":"\(order_id ?? "")","method":"app","ps_id":"\(ps_id ?? "")","changeAmount":self.change_amount,"changeDate":"\(dic["departDate"] ?? "")","ticketTime":ticketTime,"fromStationName":"\(dic["fromStationName"] ?? "")","toStationName":"\(dic["toStationName"] ?? "")","trainNo":"\(dic["trainNo"] ?? "")","arrivalDateTime":arrivalDateTime,"ticketPrice":"\(dict["maxPrice"] ?? "")","seatType":"\(dict["seatType"] ?? "")"]), completion: {[weak self] (responseString) -> (Void) in
            if self?.payType == "4"{
                //调起微信支付
                let req = PayReq.init()
                req.partnerId = "\(responseString["data"]["partnerid"])"
                req.prepayId = "\(responseString["data"]["prepayid"])"
                req.nonceStr = "\(responseString["data"]["noncestr"])"
                req.timeStamp = UInt32("\(responseString["data"]["timestamp"])") ?? 0
                req.package = "\(responseString["data"]["package"])"
                req.sign = "\(responseString["data"]["sign"])"
                WXApi.send(req, completion: nil)
            }else if self?.payType == "2"{
                //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
                let appScheme = "AirTravel"
                
                // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
                let orderString = responseString["data"].stringValue
                
                // NOTE: 调用支付结果开始支付
                AlipaySDK.defaultService()?.payOrder(orderString, fromScheme: appScheme, callback: { (resultDic) in
                    
                    print("afafa")
                })
            }
            
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    /**
     UserDefaults.standard.setValue("\(dic["orderId"] ?? "")", forKey: "xn_order_id")
     UserDefaults.standard.setValue("\(dic["contactMobile"] ?? "")", forKey: "xn_contactMobile")
     UserDefaults.standard.setValue("\(dic["departDate"] ?? "")", forKey: "xn_departDate")
     UserDefaults.standard.setValue("\(dic["arriveDate"] ?? "")", forKey: "xn_arriveDate")
     UserDefaults.standard.setValue("\(dic["departTime"] ?? "")", forKey: "xn_departTime")
     UserDefaults.standard.setValue("\(dic["arriveTime"] ?? "")", forKey: "xn_arriveTime")
     UserDefaults.standard.setValue("\(dic["fromStationName"] ?? "")", forKey: "xn_fromStationName")
     UserDefaults.standard.setValue("\(dic["toStationName"] ?? "")", forKey: "xn_toStationName")
     UserDefaults.standard.setValue("\(dic["trainNo"] ?? "")", forKey: "xn_trainNo")
     UserDefaults.standard.setValue("\(dic["useTime"] ?? "")", forKey: "xn_useTime")
     let order_passenger = dic["order_passenger"] as? Array<Any>
     if let array = order_passenger {
         let dict = array[sender.tag] as? Dictionary<String,Any>
         UserDefaults.standard.setValue("\(dict?["ps_id"] ?? "")", forKey: "xn_ps_id")
         UserDefaults.standard.setValue("\(dict?["name"] ?? "")", forKey: "xn_name")
         UserDefaults.standard.setValue("\(dict?["number"] ?? "")", forKey: "xn_number")
         UserDefaults.standard.setValue("\(dict?["ticketAmount"] ?? "")", forKey: "xn_ticketAmount")
     }
*/

}

extension TrainChangeDetailsController:ChoosePayDelegate{
    func choosePayClick(data: Dictionary<String, Any>) {
        self.payView.hide()
        self.payView.hideKeyboard()
        let key = "\(data["key"] ?? "")"
        self.payType = key
        self.orderChangePay()
    }
}
